package cn.stylefeng.guns.modular.miniapp.controller;

import org.slf4j.*;
import org.apache.commons.lang3.*;
import cn.stylefeng.guns.modular.miniapp.config.*;
import cn.stylefeng.guns.modular.miniapp.utils.*;
import me.chanjar.weixin.common.error.*;
import cn.binarywang.wx.miniapp.api.*;
import org.springframework.web.bind.annotation.*;
import cn.binarywang.wx.miniapp.bean.*;

@RestController
@RequestMapping({ "/wx/user/{appid}" })
public class WxMaUserController
{
    private final Logger logger;
    
    public WxMaUserController() {
        this.logger = LoggerFactory.getLogger((Class)this.getClass());
    }
    
    @GetMapping({ "/login" })
    public String login(@PathVariable final String appid, final String code) {
        if (StringUtils.isBlank((CharSequence)code)) {
            return "empty jscode";
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
            final WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            return JsonUtils.toJson(session);
        }
        catch (WxErrorException e) {
            this.logger.error(e.getMessage(), (Throwable)e);
            return e.toString();
        }
    }
    
    @GetMapping({ "/info" })
    public String info(@PathVariable final String appid, final String sessionKey, final String signature, final String rawData, final String encryptedData, final String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }
        final WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        return JsonUtils.toJson(userInfo);
    }
    
    @GetMapping({ "/phone" })
    public String phone(@PathVariable final String appid, final String sessionKey, final String signature, final String rawData, final String encryptedData, final String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }
        final WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        return JsonUtils.toJson(phoneNoInfo);
    }
}
